/*
 * Copyright 2005-2013 rsico. All rights reserved.
 * Support: http://www.rsico.cn
 * License: http://www.rsico.cn/license
 */
package com.rzico.core.plugin.transfer;

import com.rzico.core.entity.SysPlugin;
import com.rzico.core.plugin.TransferPlugin;
import com.rzico.util.MD5Utils;
import com.rzico.util.StringUtils;
import com.rzico.util.XMLUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Plugin - 微信付款到银行卡
 * @author rsico Team
 * @version 3.0
 */
@Component("weixinBankPlugin")
public class WeiXinBankPlugin extends TransferPlugin {

	@Value("${weixin.appid}")
	private String wx_appid;
	@Value("${weixin.mchid}")
	private String wx_mchid;
	@Value("${weixin.mchSecret}")
	private String wx_mch_secret;

	@Override
	public String getName() {
		return "微信付款到银行卡";
	}

	@Override
	public String getVersion() {
		return "1.0";
	}

	/**
	 * 作用：生成签名
	 */
	public String getSign(HashMap<String, Object> params, SysPlugin sysPlugin) throws Exception {
		String str = joinKeyValue(params,"&",true,"sign","key");
		// 签名步骤二：在string后加入KEY
		if ("1".equals(sysPlugin.getAttribute("method"))) {
			str += "&key=" + sysPlugin.getAttribute("key");
		} else {
			str += "&key=" + wx_mch_secret;
		}
		// 签名步骤三：MD5加密 签名步骤四：所有字符转为大写
		str = MD5Utils.getMD5Str(str).toUpperCase();
		return str;
	}

	@Override
	public Map<String, Object> transfer(SysPlugin sysPlugin, String userId,String sn, BigDecimal amount,String memo) {

		HashMap<String, Object> packageParams = new HashMap<>();
		HashMap<String, Object> finalpackage = new HashMap<>();
		String createNoncestr = StringUtils.CreateNoncestr();
		DecimalFormat decimalFormat = new DecimalFormat("#");
		BigDecimal money = amount.multiply(new BigDecimal(100));

		packageParams.put("mch_appid",sysPlugin.getAttribute("appid"));
		packageParams.put("mchid", sysPlugin.getAttribute("mchid"));
		packageParams.put("check_name", "NO_CHECK");
		packageParams.put("nonce_str", String.valueOf(new Date().getTime()));
		packageParams.put("partner_trade_no",sn);

		packageParams.put("amount", decimalFormat.format(money));
		packageParams.put("desc", memo);
		//packageParams.put("spbill_create_ip", IPUtils.getIp(request));
		packageParams.put("openid", userId);

		String reqUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";


		try {
			String sign = getSign(packageParams,sysPlugin);
			packageParams.put("sign", sign);


		} catch (Exception e) {
			finalpackage.put("return_code", "9999");
			finalpackage.put("error_msg", "设置异常");
			return finalpackage;
		}

		try {
			String resultXml = XMLUtils.mapToXml(packageParams);

			String respStr = post(reqUrl,resultXml,createSSLHttpClient(sysPlugin));

			Map resultMap = XMLUtils.xmlToMap(respStr);


			if("SUCCESS".equals(resultMap.get("return_code").toString())){
				if ("SUCCESS".equals(resultMap.get("result_code").toString())) {
					finalpackage.put("return_code", "0000");
					finalpackage.put("error_msg","申请成功");
				} else {
					finalpackage.put("return_code", "0003");
					finalpackage.put("error_msg", (String) resultMap.get("err_code_des"));

				}
			}else{
				finalpackage.put("return_code", "0003");
				finalpackage.put("error_msg", (String) resultMap.get("return_msg"));
			}

		} catch (Exception e) {
			finalpackage.put("return_code", "9999");
			finalpackage.put("error_msg", "设置异常");
		}
		return finalpackage;

	}

	/**
	 * 查询分账结果  0000成功  9999处理中  其他的失败
	 */
	@Override
    public Map<String, Object> query(SysPlugin sysPlugin,String sn,HttpServletRequest request) {

		HashMap<String, Object> finalpackage = new HashMap<>();
		HashMap<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("appid",sysPlugin.getAttribute("appid"));
		parameterMap.put("mch_id",sysPlugin.getAttribute("mchid"));
		parameterMap.put("partner_trade_no", sn);
		parameterMap.put("nonce_str", String.valueOf(new Date().getTime()));

		try {
			parameterMap.put("sign",getSign(parameterMap,sysPlugin));
		} catch (Exception e) {
			finalpackage.put("return_code", "0003");
			finalpackage.put("error_msg","签名出错");
			return finalpackage;
		}

		String reqUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo";
		try {
			String xml = XMLUtils.mapToXml(parameterMap);
			String resultXml = post(reqUrl,xml,createSSLHttpClient(sysPlugin));
			Map<String,Object> resultMap = XMLUtils.xmlToMap(resultXml);


			if ("SUCCESS".equals(resultMap.get("return_code").toString()) && "SUCCESS".equals(resultMap.get("result_code").toString())) {
				if ("SUCCESS".equals(resultMap.get("status").toString())) {
					finalpackage.put("return_code", "0000");
					finalpackage.put("error_msg","申请成功");
				} else if ("PROCESSING".equals(resultMap.get("status").toString())) {
					finalpackage.put("return_code", "0001");
					finalpackage.put("error_msg","等待处理");
				} else {
					finalpackage.put("return_code", "0003");
					finalpackage.put("error_msg", (String) resultMap.get("err_code_des"));
				}
			} else {
				finalpackage.put("return_code", "9999");
				finalpackage.put("error_msg", (String) resultMap.get("return_msg"));
			}


		} catch (Exception e) {
			finalpackage.put("return_code", "9999");
			finalpackage.put("error_msg", "设置异常");
		}

		return finalpackage;
	}

}